package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.base.BaseDAO;
import com.eportal.domain.AppStore;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TMirrorAgent;
import com.eportal.service.AppStoreService;
import com.eportal.service.TAgentService;
import com.eportal.util.Config;
import com.framework.jqgrid.JqGridPager;

@Service("appStoreService")
public class AppStoreServiceImpl  implements AppStoreService{
	
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(AppStoreServiceImpl.class.getName());
	
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
	private TAgentService tAgentService;
	
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	@Override
	public AppStore get(Long sid){
		AppStore tlocks = (AppStore)dao.getById(AppStore.class, sid);
		return tlocks;
	}
	
	@Override
	public List<AppStore> list(JqGridPager jqGridPager) {
		 String sql = "select t.sid,agtname as agtcode,appid,apptype,appname,TO_CHAR (t.ctime,'YYYY-MM-DD') as ctime  "
		 		+ "from "
		 		+ "(select b.*,t02_agtent.agtname from t10_appstore b left join t02_agtent on b.agtcode=t02_agtent.agtcode ) "
		 		+ "t";
	     return dao.query(sql, jqGridPager);
	}
	
	@Override
	public void delete(Long id) {
		AppStore appStore = (AppStore) dao.getById(AppStore.class, id);
        dao.delete(appStore);
	}
	@Override
	public void update(AppStore appStore) throws Exception {
        dao.update(appStore);
	}
	
	@Override
	public AppStore add(AppStore appStore) throws Exception {
		dao.save(appStore);
        return appStore;
	}
	 public Object save(Object obj) throws Exception {
	    	dao.save(obj);
	    	return obj;
	    }
	 
	 public Object get(Class clazz,Long id) {
	        return  dao.getById(clazz, id);
	    }
	  public void update(Object entity) throws Exception {
	    	try {
	    		dao.update(entity);
	        } catch (Exception e) {
	            log.error(this,e);
	        }
	        
	    }
	  public Object get(String sql) {
			return  dao.loadObject(sql);
		}
	/**
     * 应用新增保存
     */
    @LogAnnotation(operateDescribe="应用新增") 
    public Map<String, Object> addMethod(AppStore appStore, String weChatSubscription, String weChatSubId, String weChatProductId, String weChatEncodingAESKey, String weChatToken){
             try {
            	 result = new HashMap<String, Object>();
            	 long idNext  = dao.findSequence("seq_t10_appstore");
            	 String appId =  "100"+String.format("%07d", idNext);     
            	 appStore.setSid(idNext);
            	 appStore.setAppId(appId);
            	 appStore.setcTime(new Timestamp(System.currentTimeMillis()));
            	 Sysopt user= (Sysopt)getSession().getAttribute("user");
            	 appStore.setcUserName(Long.toString(user.getSid()));
            	
            	 StringBuffer sb = new StringBuffer("from TMirrorAgent where gid='");
         		 sb.append(weChatSubId);
         		 sb.append("'");
        		 TMirrorAgent tMirrorAgent = (TMirrorAgent) get(sb.toString());
        		 if(tMirrorAgent == null){
        			 tMirrorAgent = new TMirrorAgent();
//        			 tMirrorAgent.setAppId(appId);
        			 tMirrorAgent.setAgtCode(appStore.getAgtCode());
        			 tMirrorAgent.setmType("1");
        			 tMirrorAgent.setGid(weChatSubId);
        			 tMirrorAgent.setWxAppId(appStore.getWxAppId());
        			 tMirrorAgent.setWxAppSecret(appStore.getWxAppSecret());
        			 tMirrorAgent.setProductId(weChatProductId);
        			 tMirrorAgent.setcName(weChatSubscription);
        			 tMirrorAgent.setGroupToken(weChatToken);
        			 tMirrorAgent.setEncodingAesKey(weChatEncodingAESKey);
        			 tMirrorAgent.setcTime(new Timestamp(System.currentTimeMillis()));
        			 tMirrorAgent.setmOpenId(Long.toString(user.getSid()));
        			 tMirrorAgent.setGetTicketWay("1");
        			 tMirrorAgent.setGetTokenWay("1");
        			 tMirrorAgent = (TMirrorAgent) save(tMirrorAgent);
        		 }else{
        			 tMirrorAgent.setWxAppId(appStore.getWxAppId());
        			 tMirrorAgent.setWxAppSecret(appStore.getWxAppSecret());
        			 tMirrorAgent.setProductId(weChatProductId);
        			 tMirrorAgent.setcName(weChatSubscription);
        			 tMirrorAgent.setGroupToken(weChatToken);
        			 tMirrorAgent.setEncodingAesKey(weChatEncodingAESKey);
        			 tMirrorAgent.setmOpenId(Long.toString(user.getSid()));
        			 update(tMirrorAgent);
        		 }
        		 
        		 //接口新增公众号
        		 result = addWeChatSubscription(tMirrorAgent);
        		 if (!"1".equals(result.get("code").toString())) {
        			 return result;
        		 }
        		 
        		 appStore.setTmirrorAgentId(Long.toString(tMirrorAgent.getSid()));
        		 appStore = add(appStore);
            	 result.put("objectId", appStore.getSid());
            	 result.put("code", 1);
                 result.put("msg", "操作成功");
             } catch (Exception e) {
                 log.error("应用保存失败", e);
                 result.put("code", 0);
                 result.put("msg", "操作失败");
             }
         
         return result;
    }

    /**
	 * 同步微信公众号接口
	 * @param agtcode 
	 * @param pids 
	 * @param entity
	 * @return
	 */
	private Map<String, Object> addWeChatSubscription(TMirrorAgent tMirrorAgent) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String,String> map = tAgentService.getPlatAppKey(tMirrorAgent.getAgtCode());
			MdOpenBaseJson json = MdOpenApi.addWeChatSubscription(tMirrorAgent,map.get("agt_num"),map.get("app_key"));
			if(json.isSuccess()){
				result.put("code", 1);
				result.put("msg", "操作成功");
			}else{
				log.error("同步到开放平台失败，json:"+json);
				result.put("code", 2);
				result.put("msg", "同步到开放平台失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
		} catch (Exception e) {	
			log.error("同步到开放平台失败", e);
			result.put("code", 0);
			result.put("msg", "同步到开放平台失败");
		}
		return result;
	}

	
	 /**
     * 应用修改保存
     */
    @LogAnnotation(operateDescribe="应用修改") 
    public Map<String, Object> updateMethod(AppStore appStore, String weChatSubscription, String weChatSubId, String weChatProductId, String weChatEncodingAESKey, String weChatToken){
    	result = new HashMap<String, Object>();
    	result.put("objectId", appStore.getSid());
		try {
			AppStore entity = get(appStore.getSid());
			Sysopt user = (Sysopt) getSession().getAttribute("user");

			entity.setAppType(appStore.getAppType());
			entity.setAppName(appStore.getAppName());
			entity.setAndroidVer(appStore.getAndroidVer());
			entity.setAndroidVerTip(appStore.getAndroidVerTip());
			entity.setAndroidVerCode(appStore.getAndroidVerCode());
			entity.setAndroidVerLimit(appStore.getAndroidVerLimit());
			entity.setIosVer(appStore.getIosVer());
			entity.setIosVerTip(appStore.getIosVerTip());
			entity.setIosVerLimit(appStore.getIosVerLimit());
			entity.setPushAppId(appStore.getPushAppId());
			entity.setPushAppKey(appStore.getPushAppKey());
			entity.setPushAppSecret(appStore.getPushAppSecret());
			entity.setPushMasterSecret(appStore.getPushMasterSecret());
			entity.setWxAppId(appStore.getWxAppId());
			entity.setWxAppSecret(appStore.getWxAppSecret());
			entity.setIosUpdateUrl(appStore.getIosUpdateUrl());
			entity.setWxzUrl(appStore.getWxzUrl());
			entity.setWxXcxId(appStore.getWxXcxId());
			if (StringUtils.isNotBlank(appStore.getLogoImg())) {
				entity.setLogoImg(appStore.getLogoImg());	
			}
			if (StringUtils.isNotBlank(appStore.getAndroidDownloadApp())) {
				entity.setAndroidDownloadApp(appStore.getAndroidDownloadApp());
			}
			StringBuffer sb = new StringBuffer("from TMirrorAgent where gid='");
			sb.append(weChatSubId);
			sb.append("'");
			TMirrorAgent tMirrorAgent = (TMirrorAgent) get(sb.toString());
			if (tMirrorAgent == null) {
				tMirrorAgent = new TMirrorAgent();
				// tMirrorAgent.setAppId(entity.getAppId());
				tMirrorAgent.setAgtCode(entity.getAgtCode());
				tMirrorAgent.setmType("1");
				tMirrorAgent.setGid(weChatSubId);
				tMirrorAgent.setWxAppId(entity.getWxAppId());
				tMirrorAgent.setWxAppSecret(entity.getWxAppSecret());
				tMirrorAgent.setProductId(weChatProductId);
				tMirrorAgent.setcName(weChatSubscription);
				tMirrorAgent.setGroupToken(weChatToken);
				tMirrorAgent.setEncodingAesKey(weChatEncodingAESKey);
				tMirrorAgent.setcTime(new Timestamp(System.currentTimeMillis()));
				tMirrorAgent.setmOpenId(Long.toString(user.getSid()));
				tMirrorAgent.setGetTicketWay("1");
				tMirrorAgent.setGetTokenWay("1");
				tMirrorAgent = (TMirrorAgent) save(tMirrorAgent);

				entity.setTmirrorAgentId(Long.toString(tMirrorAgent.getSid()));

			} else {
				if (ifChange(tMirrorAgent, entity, weChatSubscription, weChatProductId, weChatEncodingAESKey,
						weChatToken)) {
					tMirrorAgent.setWxAppId(entity.getWxAppId());
					tMirrorAgent.setWxAppSecret(entity.getWxAppSecret());
					tMirrorAgent.setProductId(weChatProductId);
					tMirrorAgent.setcName(weChatSubscription);
					tMirrorAgent.setGroupToken(weChatToken);
					tMirrorAgent.setEncodingAesKey(weChatEncodingAESKey);
					update(tMirrorAgent);
					entity.setTmirrorAgentId(Long.toString(tMirrorAgent.getSid()));
				}
			}

			// 接口修改公众号
			result = addWeChatSubscription(tMirrorAgent);
			if (!"1".equals(result.get("code").toString())) {
				return result;
			}
			update(entity);
			result.put("code", 1);
			result.put("msg", "操作成功");
		} catch (Exception e) {
             log.error("应用更新失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
         return result;
    }

	private boolean ifChange(TMirrorAgent tMirrorAgent, AppStore entity, String weChatSubscription, String weChatProductId,
			String weChatEncodingAESKey, String weChatToken) {
		if(!tMirrorAgent.getcName().equals(weChatSubscription)){
			return true;
		}
		if(!tMirrorAgent.getProductId().equals(weChatProductId)){
			return true;
		}
		if(!tMirrorAgent.getWxAppId().equals(entity.getWxAppId())){
			return true;
		}
		if(!tMirrorAgent.getWxAppSecret().equals(entity.getWxAppSecret())){
			return true;
		}
		if(!tMirrorAgent.getEncodingAesKey().equals(weChatEncodingAESKey)){
			return true;
		}
		if(!tMirrorAgent.getGroupToken().equals(weChatToken)){
			return true;
		}
		return false;
	}

	

	@Override
	public List<AppStore> list(String hql) {
		return dao.query(hql);
	}

	@Override
	public Map<String, String> getBySql(Long sid) {
		List<Map<String, String>> list= null;
		StringBuilder sql = new StringBuilder("select b.sid,b.appid,b.appType,b.appName,b.appVersion,b.updateLog,b.PUSH_APP_ID,b.android_download_app,b.push_app_secret,b.push_app_key,b.push_master_secret,b.android_Ver,b.ios_Ver,b.android_Ver_Tip,b.ios_Ver_Tip,b.android_Ver_Limit,b.ios_Ver_Limit,b.android_Ver_Code,b.ios_Update_Url,b.wxz_Url,b.download_img1,b.download_img2,b.logo_img,b.wx_xcx_id"
				+ ",t02_agtent.agtname,tm.gid,tm.wx_app_id,tm.wx_app_secret,tm.product_id,tm.cname as cname1,tm.grouptoken,tm.encodingaeskey,"
				+ "(select XMLAGG(XMLELEMENT(E, c.communityname || ',')).EXTRACT('//text()').getclobval() from T03_COMMUNITY c where c.appid=b.appid) as cname "
				+ "from t10_appstore b  "
				+ "left join t02_agtent on b.agtcode=t02_agtent.agtcode  "
				+ "left join tmirror_agent tm on b.tmirroragentid=tm.sid "
				+ "where b.sid=");
		sql.append(sid);
		list= dao.queryBySql(sql.toString());
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	
	
}
